package com.efounder.message.socket;

import android.os.Build;
import android.os.Handler;
import android.util.Log;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.AppContext;
import com.efounder.util.BaseDeviceUtils;

import net.sf.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * 登录权限日志管理
 */
public class JFAuthManager {

    private static final String TAG = "JFAuthManager";
    private volatile static  JFAuthManager jfAuthManager;
    private Handler requestHandler;//全局处理子线程和M主线程通信
    //是否已经检查权限
    private boolean hasChecked;


    public static JFAuthManager getInstance() {
        if (jfAuthManager == null) {
            synchronized (JFAuthManager.class) {
                jfAuthManager = new JFAuthManager();
            }
        }
        return jfAuthManager;
    }

    public JFAuthManager() {
        // requestHandler = new Handler(Looper.getMainLooper());
    }

    public void requestAuth() {
        if (hasChecked) {
            return;
        }
        Map<String, String> paramMap = new HashMap();
//        @ApiImplicitParam(name = "appId", paramType = "query", value = "openplanet", required = true, dataType = "string"),
//        @ApiImplicitParam(name = "imUserId", paramType = "query", value = "", required = true, dataType = "string"),
//        @ApiImplicitParam(name = "deviceType", paramType = "query", value = "android ios", required = true, dataType = "string"),
//        @ApiImplicitParam(name = "deviceVersion", paramType = "query", value = "设备系统版本", example = "android 4.4", required = true, dataType = "string"),
//        @ApiImplicitParam(name = "loginUserId", paramType = "query", value = "183638xxxxx", required = true, dataType = "string"),
//        @ApiImplicitParam(name = "nickName", paramType = "query", value = "松11", required = true, dataType = "string"),
//        @ApiImplicitParam(name = "deviceBrand", paramType = "query", value = "huawei", required = true, dataType = "string"),
//        @ApiImplicitParam(name = "deviceModel", paramType = "query", value = "huawei-v10", required = true, dataType = "string"),
//        @ApiImplicitParam(name = "deviceUniqueId", paramType = "query", value = "设备唯一id", required = true, dataType = "string"),
//        @ApiImplicitParam(name = "loginIp", paramType = "query", value = "登录的ip", required = true, dataType = "string"),

        paramMap.put("appId", EnvironmentVariable.getProperty("APPID"));
        paramMap.put("imUserId", EnvironmentVariable.getProperty("chatUserId",""));
        paramMap.put("loginUserId", EnvironmentVariable.getUserName());
        paramMap.put("deviceType", "Android");
        paramMap.put("deviceVersion", BaseDeviceUtils.getSDKVersionName());
        paramMap.put("nickName", EnvironmentVariable.getProperty("NickName",""));
        paramMap.put("deviceBrand", BaseDeviceUtils.getDeviceBrand());
        paramMap.put("deviceModel", BaseDeviceUtils.getDeviceModel());
        paramMap.put("deviceUniqueId", BaseDeviceUtils.getUniqueId(AppContext.getInstance()));
        paramMap.put("loginIp", BaseDeviceUtils.getIPAddress(AppContext.getInstance()) + "");
        paramMap.put("appName", BaseDeviceUtils.getAppName() + "");
        paramMap.put("appVersion", BaseDeviceUtils.getAppVersion() + "");
        JSONObject jsonObject = JSONObject.fromObject(paramMap);
        requestServer(jsonObject);

    }

    //请求服务器
    private void requestServer(final JSONObject jsonObject) {
//        final String requestUrl = EnvironmentVariable.getProperty("mobileAuthUrl",
//                "https://mobile.solarsource.cn/MobileAuth/loginAuth/v1");
        final String requestUrl = EnvironmentVariable.getProperty("mobileAuthUrl",
                "http://mobile-server.openserver.cn/MobileAuth/loginAuth/v1");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(requestUrl);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

//                    boolean useHttps = requestUrl.startsWith("https");
//                    SSLSocketFactory oldSocketFactory = null;
//                    HostnameVerifier oldHostnameVerifier = null;
//                    if (useHttps) {
//                        HttpsURLConnection https = (HttpsURLConnection) connection;
//                        oldSocketFactory = trustAllHosts(https);
//                        oldHostnameVerifier = https.getHostnameVerifier();
//                        https.setHostnameVerifier(DO_NOT_VERIFY);
//                    }
                    httpURLConnection.setRequestMethod("POST");// 提交模式
                    httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
                    httpURLConnection.setReadTimeout(2000);//读取超时 单位毫秒

                    // 设置文件类型:
                    httpURLConnection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
                    // 发送POST请求必须设置如下两行
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);
                    // 获取URLConnection对象对应的输出流
                    PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
                    // 发送请求参数
                    printWriter.write(jsonObject.toString());//post的参数 xx=xx&yy=yy
                    // flush输出流的缓冲
                    printWriter.flush();


                    if (httpURLConnection.getResponseCode() == 200) {
                        //设置已检查权限
                        hasChecked = true;
                        //开始获取数据
                        BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        int len;
                        byte[] arr = new byte[1024];
                        while ((len = bis.read(arr)) != -1) {
                            bos.write(arr, 0, len);
                            bos.flush();
                        }

                        String result = bos.toString("utf-8");
                        Log.d(TAG, result + "");
                        JSONObject jsonObject = JSONObject.fromObject(result);
                        if (jsonObject.optString("result", "").equals("fail")) {
                            if (jsonObject.optString("msg", "").equals("permission refused")) {
                                //没有权限 ，杀死应用
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                    try {
                                        AppContext.getCurrentActivity().finishAffinity();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                android.os.Process.killProcess(android.os.Process.myPid());
                                System.exit(0);
                            }
                        }
                        bos.close();
                    }
                    httpURLConnection.disconnect();

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }).start();

    }

    /**
     * 覆盖java默认的证书验证
     */
    private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
    }};

    /**
     * 设置不验证主机
     */
    private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    /**
     * 信任所有
     * @param connection
     * @return
     */
    private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
        SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            SSLSocketFactory newFactory = sc.getSocketFactory();
            connection.setSSLSocketFactory(newFactory);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return oldFactory;
    }
    /**
     * 从map中获取请求参数
     *
     * @param map
     * @return
     */
    private static String getRequstParamFromMap(Map<String, String> map) {
        StringBuilder tempParams = new StringBuilder();
        try {
            //处理参数
            int pos = 0;
            for (String key : map.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                //对参数进行URLEncoder
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(map.get(key), "utf-8")));
                pos++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tempParams.toString();

    }
}
